package zxs.sino.elite.hub.config.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import zxs.sino.elite.hub.model.model.UserModel;
import zxs.sino.elite.hub.utils.JwtUtil;
import zxs.sino.elite.hub.utils.RedisKeys;
import zxs.sino.elite.hub.utils.RedisUtil;
import zxs.sino.elite.hub.utils.UserContext;

import java.io.IOException;
import java.util.ArrayList;

/**
 * JWT认证过滤器
 * 用于验证请求中的JWT令牌并设置Spring Security的认证上下文
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {

        // 对于/api/**路径，直接跳过JWT验证
//        String requestURI = request.getRequestURI();
//        if (requestURI.startsWith("/api/")) {
//            filterChain.doFilter(request, response);
//            return;
//        }

        try {
            // 获取请求头中的JWT令牌
            String jwt = getJwtFromRequest(request);

            // 如果请求中包含JWT令牌，且令牌有效，则验证并设置认证上下文
            if (StrUtil.isNotBlank(jwt) && jwtUtil.validateToken(jwt)) {
                // 解析JWT令牌获取用户信息
                UserModel userInfo = jwtUtil.getUserInfoFromToken(jwt);

                // 从Redis中验证令牌是否有效
                String storedToken = (String) redisUtil.get(RedisKeys.getRoleKey(userInfo.getRole(), userInfo.getAuthKey()));
                if (StrUtil.isEmpty(storedToken) || !storedToken.equals(jwt)) {
                    // 令牌无效或已过期
                    sendErrorResponse(response, "Token is invalid or expired");
                    return;
                }

                // 设置用户上下文
                UserContext.setUserInfo(userInfo);

                // 创建认证对象并设置到Spring Security上下文中
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userInfo, null, new ArrayList<>());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                // 设置认证信息到安全上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            logger.error("Could not set user authentication in security context", e);
            sendErrorResponse(response, "Authentication failed: " + e.getMessage());
            return;
        }

        // 继续过滤器链
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求头中获取JWT令牌
     */
    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
//        response.getWriter().write(new Gson().toJson(R.error().put("msg", message)));
    }
}